import json, time
from multiprocessing import Process


# 多进程同时打开操作同一个文件，就会出现资源冲突导致的报错问题。
# 这里体现的就是多进程并发/并行情况下会带来数据操作的过程中一致性问题。（表现在商品超卖，转账结果出错等情况）


def get_ticket(username):
    """查询余票"""
    time.sleep(0.01)
    data = json.load(open("ticket.txt", "r"))
    print(f"{username}查询余票：{data['count']}")


def buy_ticket(username):
    """购买车票"""
    time.sleep(0.01)
    data = json.load(open("ticket.txt", "r"))

    # 判断如果有票，则购买
    if data["count"] > 0:
        data["count"] -= 1  # 买票
        print(f"{username}购买车票成功!")
    else:
        print(f"{username}购买车票失败!")
    time.sleep(0.01)
    json.dump(data, open("ticket.txt", "w"))


def task(username):
    """购票流程"""
    get_ticket(username)
    buy_ticket(username)


if __name__ == '__main__':
    for i in range(10):
        p = Process(target=task, args=(f"user-{i}",))
        p.start()
